(ns acst.models.users
  (:use acst.config.error-config)
  (:require [acst.models.db :as db]
            [acst.models.roles :as role]
            [acst.utils.sql-util :as sqlutil]
            [clojure.java.jdbc :as sql]
            [noir.session :as session]
            [clojure.data.json :as json]))


(defn register! [username password]
  (db/insert! :users
              {:username username
               :password password
               :permission (role/user-role :permission)}))

(defn update-user-permission! [username permission]
  (db/update! :users
              {:username username
               :permission permission}
              ["username = ?" username]))

(defn update-user! [username password number mobile]
  (db/update! :users
              (-> {:username username            ;;避免全为nil错误
                   :password password
                   :number number
                   :mobile mobile}
                  (sqlutil/filter-nil))
              ["username = ?" username]))

(defn find-password [username]
  (db/query
    (:user-not-register users-error)
    ["SELECT user_id, password FROM users WHERE username = ?" username]))

(defn find-user  [username]
  (db/query
    (:user-not-register users-error)
    ["SELECT user_id, username, number mobile FROM users WHERE username = ?" username]))

(defn find-all-users [limit page]
  (db/query
    (:user-not-register users-error)
    ["SELECT user_id, username, number, mobile FROM users ORDER BY user_id LIMIT ? OFFSET" limit (* (- page 1) limit)]))

(defn set-user-session! [username user_id]
  (do
    (session/put! "username" username)
    (session/put! "user_id" user_id)))

(defn rm-user-session! []
  {:username (session/get! "username") :user_id (session/get! "user_id")})


(defmacro login-require [ & body]
  `(if (nil? (session/get "user_id")) (json/write-str (:not-login users-error)) ~@body))

(defmacro admin-require [& body]
  `(if (role/is-admin? (session/get "user_id")) ~@body (json/write-str (:not-admin users-error))))